<?php

/*
 * 定义日期的显示格式
 * 在loop-index.php中被引用
 * 覆盖父主题twentyten里的同名函数
 *
 * @since kiwi 1.0
 */
function twentyten_posted_on() {
	printf( __( '<span class="%1$s">%2$s</span>', 'twentyten' ),
		'date',
		sprintf( '<span class="entry-date">%1$s</span>',
			get_the_date("Y.m.d H:i")
		)
	);
}

/*
 * 定义“边栏”
 * “边栏”是用于容纳小挂件widgets的一个容器
*/
function kiwi_widgets_init() {
	//
	register_sidebar( array(
		'name' => __( '边栏', 'kiwi' ),
		'id' => 'primary-widget-area',
		'description' => __( '边栏', 'kiwi' ),
		'before_widget' => '<li id="%1$s" class="widget-container %2$s">',
		'after_widget' => '</li>',
		'before_title' => '<h3 class="widget-title">',
		'after_title' => '</h3>',
	) );
}

/* 去掉父主题的widget栏初始化，然后加上自己的widget初始化
 * 由于之后等父主题的add_action生效之后才能remove_action
 * 所以需要把整个动作封装在kiwi_child_theme_setup中
 * 然后绑定after_setup_theme动作
 */
add_action('after_setup_theme','kiwi_child_theme_setup');
function kiwi_child_theme_setup(){
	remove_action( 'widgets_init', 'twentyten_widgets_init' );
	add_action('widgets_init','kiwi_widgets_init');
}

/**
 * 覆盖父主题的初始化
 * 主要是去掉了父主题的header头图定义功能
 */
function twentyten_setup() {

	// This theme styles the visual editor with editor-style.css to match the theme style.
	add_editor_style();

	// This theme uses post thumbnails
	add_theme_support( 'post-thumbnails' );

	// Add default posts and comments RSS feed links to head
	add_theme_support( 'automatic-feed-links' );

	// Make theme available for translation
	// Translations can be filed in the /languages/ directory
	load_theme_textdomain( 'twentyten', TEMPLATEPATH . '/languages' );

	$locale = get_locale();
	$locale_file = TEMPLATEPATH . "/languages/$locale.php";
	if ( is_readable( $locale_file ) )
		require_once( $locale_file );

	// This theme uses wp_nav_menu() in one location.
	register_nav_menus( array(
		'primary' => __( 'Primary Navigation', 'twentyten' ),
	) );

	// 允许自定义上传背景图片
	add_custom_background();
}


/* 把函数绑定在widgets_init钩子上 */
add_action( 'widgets_init', 'social_cn_load_widgets' );

/* 用于注册我们的小挂件的函数 */
function social_cn_load_widgets() {
	register_widget( 'Social_Cn_Widget' );
	register_widget( 'RSS_Widget' );
	register_widget( 'Feature_Image_Widget' );

}



/**
* 定义一个自定义的widget，用来在后台接受用户社交网络url
* 在functions.php中被注册
*
*
* @since kiwi 1.0
*/
class Social_Cn_Widget extends WP_Widget {

	/**
	 * 初始函数
	 */
	function Social_Cn_Widget() {
		/* Widget 设定 */
		$widget_ops = array( 'classname' => 'social_cn_widget', 'description' => '显示用户社交网络链接' );

		/* Widget 控制设定 */
		$control_ops = array( 'id_base' => 'social_cn_widget' );

		/* 创建widget*/
		$this->WP_Widget( 'social_cn_widget', 'kiwi:中文社交挂件', $widget_ops, $control_ops );
	}

	/**
	 * 在前台页面显示widget
	 */
	function widget( $args, $instance ) {
		extract( $args );

		/* 获取用户选择或者输入的数据 */
		$title = apply_filters('widget_title', $instance['title'] );
		$show_title = isset( $instance['show_title'] ) ? $instance['show_title'] : false;
		$tencent = $instance['tencent'];
		$sina = $instance['sina'];
		$twitter = $instance['twitter'];
		$renren = $instance['renren'];
		$qzone = $instance['qzone'];
		$douban = $instance['douban'];

		/* 在输出widget之前 ($before_widget由主题定义). */
		echo $before_widget;

		/* 显示标题($before_title和$after_title由主题定义). */
		if ( $show_title )
			echo $before_title . $title . $after_title;

		/* 显示腾讯围脖 */
		if ( $tencent )
			echo '<a class="ico_sn tqq" href="'. $tencent .'" title="腾讯微博">腾讯微博</a>';

		/* 显示新浪围脖 */
		if ( $sina )
			echo '<a class="ico_sn tsina" href="'. $sina .'" title="新浪微博">新浪微博</a>';

		/* 显示twitter */
		if ( $twitter )
			echo '<a class="ico_sn twitter" href="'. $twitter .'" title="Twitter">Twitter</a>';

		/* 显示人人网 */
		if ( $renren )
			echo '<a class="ico_sn rr" href="'. $renren .'" title="人人网">人人网</a>';

		/* 显示qzone */
		if ( $qzone )
			echo '<a class="ico_sn qz" href="'. $qzone .'" title="Qzone">Qzone</a>';

		/* 显示豆瓣 */
		if ( $douban )
			echo '<a class="ico_sn db" href="'. $douban .'" title="豆瓣">豆瓣</a>';


		/* After widget (defined by themes). */
		echo $after_widget;
	}

	function update( $new_instance, $old_instance ) {
		$instance = $old_instance;

		/* Strip tags (if needed) and update the widget settings. */
		$instance['title'] = strip_tags( $new_instance['title'] );
		$instance['show_title'] = $new_instance['show_title'];
		$instance['tencent'] = strip_tags( $new_instance['tencent'] );
		$instance['sina'] = strip_tags( $new_instance['sina'] );
		$instance['twitter'] = strip_tags( $new_instance['twitter'] );
		$instance['renren'] = strip_tags( $new_instance['renren'] );
		$instance['qzone'] = strip_tags( $new_instance['qzone'] );
		$instance['douban'] = strip_tags( $new_instance['douban'] );

		return $instance;
	}

	/**
	 * 后台设置
	 * 在widget面板显示设置选项
	 * 可以让用户分别输入各个社交网站的用户名或者地址，从而在前台页面显示链接
	 */
	function form( $instance ) {

		/* 默认设置 */
		$defaults = array( 'title' => __('我的社交', 'kiwi'), 'tencent' => __('http://t.qq.com/chandleryu', 'kiwi'), 'twitter' => __('http://twitter.com/yuguo', 'kiwi'),
			'sina' => __('', 'kiwi'), 'renren' => __('', 'kiwi'), 'qzone' => __('', 'kiwi'), 'douban' => __('', 'kiwi'),
			'show_title'=>false );
		$instance = wp_parse_args( (array) $instance, $defaults );?>

		<!-- widget标题 —— 文本输入 -->
		<p>
			<?php $title="title"; ?>
			<label for="<?php echo $this->get_field_id( $title ); ?>"><?php _e('标题', 'kiwi'); ?></label>
			<input id="<?php echo $this->get_field_id($title ); ?>" name="<?php echo $this->get_field_name( $title ); ?>" value="<?php echo $instance[$title]; ?>" style="width:95%;" />
		</p>

		<!-- 是否显示标题 —— checkbox -->
		<p>
			<input class="checkbox" type="checkbox" <?php checked( $instance['show_title'], 'on' ); ?> id="<?php echo $this->get_field_id( 'show_title' ); ?>" name="<?php echo $this->get_field_name( 'show_title' ); ?>" />
			<label for="<?php echo $this->get_field_id( 'show_title' ); ?>"><?php _e('显示标题', 'kiwi'); ?></label>
		</p>

		<p class="description">请在下列输入框中输入完整的url，比如：http://t.qq.com/chandleryu</p>

		<!-- 腾讯微博 —— 文本输入 -->
		<p>
			<label for="<?php echo $this->get_field_id( 'tencent' ); ?>"><?php _e('腾讯微博', 'kiwi'); ?></label><br/>
			<input id="<?php echo $this->get_field_id( 'tencent' ); ?>" name="<?php echo $this->get_field_name( 'tencent' ); ?>" value="<?php echo $instance['tencent']; ?>" style="width:95%;" />
		</p>

		<!-- 新浪微博 —— 文本输入 -->
		<p>
			<label for="<?php echo $this->get_field_id( 'sina' ); ?>"><?php _e('新浪微博', 'kiwi'); ?></label><br/>
			<input id="<?php echo $this->get_field_id( 'sina' ); ?>" name="<?php echo $this->get_field_name( 'sina' ); ?>" value="<?php echo $instance['sina']; ?>" style="width:95%;" />
		</p>

		<!-- twitter —— 文本输入 -->
		<p>
			<label for="<?php echo $this->get_field_id( 'twitter' ); ?>"><?php _e('Twitter', 'kiwi'); ?></label><br/>
			<input id="<?php echo $this->get_field_id( 'twitter' ); ?>" name="<?php echo $this->get_field_name( 'twitter' ); ?>" value="<?php echo $instance['twitter']; ?>" style="width:95%" />
		</p>

		<!-- 人人网 —— 文本输入 -->
		<p>
			<label for="<?php echo $this->get_field_id( 'renren' ); ?>"><?php _e('人人网', 'kiwi'); ?></label><br/>
			<input id="<?php echo $this->get_field_id( 'renren' ); ?>" name="<?php echo $this->get_field_name( 'renren' ); ?>" value="<?php echo $instance['renren']; ?>" style="width:95%" />
		</p>

		<!-- qzone—— 文本输入 -->
		<p>
			<label for="<?php echo $this->get_field_id( 'qzone' ); ?>"><?php _e('Qzone', 'kiwi'); ?></label><br/>
			<input id="<?php echo $this->get_field_id( 'qzone' ); ?>" name="<?php echo $this->get_field_name( 'qzone' ); ?>" value="<?php echo $instance['qzone']; ?>" style="width:95%" />
		</p>

		<!-- 豆瓣 —— 文本输入 -->
		<p>
			<label for="<?php echo $this->get_field_id( 'douban' ); ?>"><?php _e('豆瓣', 'kiwi'); ?></label><br/>
			<input id="<?php echo $this->get_field_id( 'douban' ); ?>" name="<?php echo $this->get_field_name( 'douban' ); ?>" value="<?php echo $instance['douban']; ?>" style="width:95%;" />
		</p>
	<?php
	}
}

/**
* 定义一个自定义的widget，用来显示RSS链接的文字
* 在functions.php中被注册
*
*
* @since kiwi 1.0
*/
class RSS_Widget extends WP_Widget {

	/**
	 * 初始函数
	 */
	function RSS_Widget() {
		/* Widget 设定 */
		$widget_ops = array( 'classname' => 'rss_widget', 'description' => '显示一个RSS链接和提示文字' );

		/* Widget 控制设定 */
		$control_ops = array( 'id_base' => 'rss_widget' );

		/* 创建widget*/
		$this->WP_Widget( 'rss_widget', 'kiwi:RSS订阅', $widget_ops, $control_ops );
	}

	/**
	 * 在前台页面显示widget
	 */
	function widget( $args, $instance ) {
		extract( $args );

		/* 获取用户选择或者输入的数据 */
		$title = apply_filters('widget_title', $instance['title'] );
		$rss_title = apply_filters('widget_title', $instance['rss_title'] );

		/* 在输出widget之前 ($before_widget由主题定义). */
		echo $before_widget;

		/* 显示标题($before_title和$after_title由主题定义). */
		if ( $title ) ?>
			<a href='<?php bloginfo("rss2_url"); ?>' title='<?php echo $rss_title;?>'><b class="rss_ico"></b><span class="rss_intro"><?php echo $title; ?></span></a>
		<?php

		/* After widget (defined by themes). */
		echo $after_widget;
	}

	function update( $new_instance, $old_instance ) {
		$instance = $old_instance;

		/* Strip tags (if needed) and update the widget settings. */
		$instance['title'] = strip_tags( $new_instance['title'] );
		$instance['rss_title'] = strip_tags( $new_instance['rss_title'] );
		return $instance;
	}

	/**
	 * 后台设置
	 * 在widget面板显示设置选项
	 * 可以让用户分别输入显示的RSS名称和链接提示文字
	 */
	function form( $instance ) {

		/* 默认设置 */
		$defaults = array( 'title' => __('ADD TO READER', 'kiwi'),'rss_title' => __('欢迎订阅RSS', 'kiwi') );
		$instance = wp_parse_args( (array) $instance, $defaults );?>

		<!-- widget显示文字 —— 文本输入 -->
		<p>
			<?php $title="title"; ?>
			<label for="<?php echo $this->get_field_id( $title ); ?>"><?php _e('Title:', 'kiwi'); ?></label>
			<input id="<?php echo $this->get_field_id($title ); ?>" name="<?php echo $this->get_field_name( $title ); ?>" value="<?php echo $instance[$title]; ?>" style="width:95%;" />
		</p>

		<!-- widget链接提示 —— 文本输入 -->
		<p>
			<label for="<?php echo $this->get_field_id( $rss_title ); ?>"><?php _e('链接提示文字:', 'kiwi'); ?></label>
			<input id="<?php echo $this->get_field_id( 'rss_title' ); ?>" name="<?php echo $this->get_field_name( 'rss_title' ); ?>" value="<?php echo $instance['rss_title']; ?>" style="width:95%;" />
		</p>
	<?php
	}
}

/**
* 定义一个自定义的widget，用来显示需要显示Feature-image的文章列表的Feature-image
* 在functions.php中被注册
*
*
* @since kiwi 1.0
*/
class Feature_Image_Widget extends WP_Widget {

	/**
	 * 初始函数
	 */
	function Feature_Image_Widget() {
		/* Widget 设定 */
		$widget_ops = array( 'classname' => 'feature_image_widget', 'description' => '显示需要显示Feature-image的文章列表的Feature-image' );

		/* Widget 控制设定 */
		$control_ops = array( 'id_base' => 'feature_image_widget' );

		/* 创建widget*/
		$this->WP_Widget( 'feature_image_widget', 'kiwi:文章缩略图', $widget_ops, $control_ops );
	}

	/**
	 * 在前台页面显示widget
	 */
	function widget( $args, $instance ) {
		extract( $args );

		/* 获取用户选择或者输入的数据 */
		$show_number = apply_filters('widget_title', $instance['show_number'] );

		/* 在输出widget之前 ($before_widget由主题定义). */
		echo $before_widget;

		echo "<ul>";
		global $post;
		$myposts = get_posts('numberposts=5&category="feature"');
		foreach($myposts as $post) :
		setup_postdata($post);
		?>
			<li class="feature-item">
				<?php if ( has_post_thumbnail() ) {
				?>
					<a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>" rel="bookmark">
						<?php the_post_thumbnail( 'thumbnail' ); ?>
					</a>
				<?php } ?>
			</li>
	 <?php endforeach;

		echo "</ul>";
		/* After widget (defined by themes). */
		echo $after_widget;
	}

	function update( $new_instance, $old_instance ) {
		$instance = $old_instance;

		/* Strip tags (if needed) and update the widget settings. */
		$instance['show_number'] = strip_tags( $new_instance['show_number'] );
		return $instance;
	}

	/**
	 * 后台设置
	 * 在widget面板显示设置选项
	 * 可以让用户分别输入显示的RSS名称和链接提示文字
	 */
	function form( $instance ) {

		/* 默认设置 */
		$defaults = array( 'show_number' => __('3', 'kiwi') );
		$instance = wp_parse_args( (array) $instance, $defaults );?>

		<!-- 显示缩略图的条目数量 —— 文本输入 -->
		<p>
			<label for="<?php echo $this->get_field_id( $show_number ); ?>"><?php _e('显示缩略图的条目数量:', 'kiwi'); ?></label>
			<input id="<?php echo $this->get_field_id(show_number ); ?>" name="<?php echo $this->get_field_name( show_number ); ?>" value="<?php echo $instance[show_number]; ?>" style="width:95%;" />
		</p>

	<?php
	}
}

/* 修改缩略图的大小 */
add_filter( 'post_thumbnail_size', 'my_post_image_size' );

function my_post_image_size( $size ) {
	$size = 'thumbnail';
	return $size;
}

/*
 * 以下代码根据插件 FeedBurner FeedSmith 修改而来，用于自定义RSS地址
 *
*/

$data = array(
	'feedburner_url'		=> '',
	'feedburner_comments_url'	=> ''
);

$ol_flash = '';

function ol_is_authorized() {
	global $user_level;
	if (function_exists("current_user_can")) {
		return current_user_can('activate_plugins');
	} else {
		return $user_level > 5;
	}
}

add_option('feedburner_settings',$data,'FeedBurner Feed Replacement Options');

$feedburner_settings = get_option('feedburner_settings');

function fb_is_hash_valid($form_hash) {
	$ret = false;
	$saved_hash = fb_retrieve_hash();
	if ($form_hash === $saved_hash) {
		$ret = true;
	}
	return $ret;
}

function fb_generate_hash() {
	return md5(uniqid(rand(), TRUE));
}

function fb_store_hash($generated_hash) {
	return update_option('feedsmith_token',$generated_hash,'FeedSmith Security Hash');
}

function fb_retrieve_hash() {
	$ret = get_option('feedsmith_token');
	return $ret;
}

function ol_add_feedburner_options_page() {
	if (function_exists('add_options_page')) {
		add_submenu_page('themes.php','FeedBurner', 'Custom RSS', 8, basename(__FILE__), 'ol_feedburner_options_subpanel');
	}
}

function ol_feedburner_options_subpanel() {
	global $ol_flash, $feedburner_settings, $_POST, $wp_rewrite;
	if (ol_is_authorized()) {
		// Easiest test to see if we have been submitted to
		if(isset($_POST['feedburner_url']) || isset($_POST['feedburner_comments_url'])) {
			// Now we check the hash, to make sure we are not getting CSRF
			if(fb_is_hash_valid($_POST['token'])) {
				if (isset($_POST['feedburner_url'])) {
					$feedburner_settings['feedburner_url'] = $_POST['feedburner_url'];
					update_option('feedburner_settings',$feedburner_settings);
					$ol_flash = "Your settings have been saved.";
				}
				if (isset($_POST['feedburner_comments_url'])) {
					$feedburner_settings['feedburner_comments_url'] = $_POST['feedburner_comments_url'];
					update_option('feedburner_settings',$feedburner_settings);
					$ol_flash = "Your settings have been saved.";
				}
			} else {
				// Invalid form hash, possible CSRF attempt
				$ol_flash = "Security hash missing.";
			} // endif fb_is_hash_valid
		} // endif isset(feedburner_url)
	} else {
		$ol_flash = "You don't have enough access rights.";
	}

	if ($ol_flash != '') echo '<div id="message" class="updated fade"><p>' . $ol_flash . '</p></div>';

	if (ol_is_authorized()) {
		$temp_hash = fb_generate_hash();
		fb_store_hash($temp_hash);
		echo '<div class="wrap">';
		echo '<h2>设置你的RSS Feed地址</h2>';
		echo '<p>如果你需要将wordpress提供的RSS地址100%转到自己烧录的RSS地址——比如feedsky或者Feedburner——以便统计数据或者扩展（比如添加广告或版权），你需要做的就是在下面填入你的烧录地址。如果你不需要统计RSS和添加版权，无需理会本页。</p>
		<form action="" method="post">
		<input type="hidden" name="redirect" value="true" />
		<input type="hidden" name="token" value="' . fb_retrieve_hash() . '" />
		<ol>
		<li>如果你还没有烧录自己的RSS，请访问 <a href="https://www.feedburner.com/fb/a/addfeed?sourceUrl=' . get_bloginfo('url') . '" target="_blank">create a FeedBurner feed for ' . get_bloginfo('name') . '</a>. 它会自动抓取你的所有文章更新（评论更新是可选的），并生成一个新的烧录地址。</li>
		<li>如果你有自己的烧录地址，那么在下面输入你的烧录的RSS地址 (http://feeds.feedburner.com/yourfeed):<br/><input type="text" name="feedburner_url" value="' . htmlentities($feedburner_settings['feedburner_url']) . '" size="45" /></li>
		<li>可选: 如果你想把你的评论RSS也烧录，那么<a href="https://www.feedburner.com/fb/a/addfeed?sourceUrl=' . get_bloginfo('url') . '/wp-commentsrss2.php" target="_blank">烧录一个Feedburner的评论RSS</a>之后再输入你的烧录的RSS地址:<br/><input type="text" name="feedburner_comments_url" value="' . htmlentities($feedburner_settings['feedburner_comments_url']) . '" size="45" />
		</ol>
		<p><input type="submit" value="保存" /></p></form>
		<p>注：以上给出的链接都是Feedburner的烧录地址，您可以用国内的<a href="http://www.feedsky.com/" title="Feedsky">Feedsky</a>或者任何烧录商提供的URL。Feedburner是国外烧录商，在国内访问可能会出现众所周知的问题。</p>
		';
		echo '</div>';
	} else {
		echo '<div class="wrap"><p>Sorry, you are not allowed to access this page.</p></div>';
	}

}

function ol_feed_redirect() {
	global $wp, $feedburner_settings, $feed, $withcomments;
	if (is_feed() && $feed != 'comments-rss2' && !is_single() && $wp->query_vars['category_name'] == '' && ($withcomments != 1) && trim($feedburner_settings['feedburner_url']) != '') {
		if (function_exists('status_header')) status_header( 302 );
		header("Location:" . trim($feedburner_settings['feedburner_url']));
		header("HTTP/1.1 302 Temporary Redirect");
		exit();
	} elseif (is_feed() && ($feed == 'comments-rss2' || $withcomments == 1) && trim($feedburner_settings['feedburner_comments_url']) != '') {
		if (function_exists('status_header')) status_header( 302 );
		header("Location:" . trim($feedburner_settings['feedburner_comments_url']));
		header("HTTP/1.1 302 Temporary Redirect");
		exit();
	}
}

function ol_check_url() {
	global $feedburner_settings;
	switch (basename($_SERVER['PHP_SELF'])) {
		case 'wp-rss.php':
		case 'wp-rss2.php':
		case 'wp-atom.php':
		case 'wp-rdf.php':
			if (trim($feedburner_settings['feedburner_url']) != '') {
				if (function_exists('status_header')) status_header( 302 );
				header("Location:" . trim($feedburner_settings['feedburner_url']));
				header("HTTP/1.1 302 Temporary Redirect");
				exit();
			}
			break;
		case 'wp-commentsrss2.php':
			if (trim($feedburner_settings['feedburner_comments_url']) != '') {
				if (function_exists('status_header')) status_header( 302 );
				header("Location:" . trim($feedburner_settings['feedburner_comments_url']));
				header("HTTP/1.1 302 Temporary Redirect");
				exit();
			}
			break;
	}
}

if (!preg_match("/feedburner|feedvalidator/i", $_SERVER['HTTP_USER_AGENT'])) {
	add_action('template_redirect', 'ol_feed_redirect');
	add_action('init','ol_check_url');
}

add_action('admin_menu', 'ol_add_feedburner_options_page');

?>
